<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { FormType } from './fukaTaskDetail'
import { GetFukaOption, GetTaskDataDetail, PostTaskCreateData, PutTaskModifyData } from '@/api/modules/fukaact'
import detailStore from '@/store/modules/NewCacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  fukaActId: route.query.fukaActId ? Number(route.query.fukaActId) : '',
  classId: '',
  taskPic: '',
  taskStatus: -1,
  linkUrl: '',
  sort: 0,
})

const id = route.query.id as string

const rules = reactive({
  fukaActId: [
    { required: true, message: '请选择福卡活动', trigger: 'blur' },
  ],
  productId: [
    { required: true, message: '请选择要关联的商品', trigger: 'blur' },
  ],
})

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  // eslint-disable-next-line ts/ban-ts-comment
  // @ts-expect-error
  ruleForm.value[key] = url
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }
      // console.log(params)

      if (id) {
        // 编辑
        params.fukaTaskId = Number(id)
        PutTaskModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({
              name: 'fukaTaskList',
              query: {
                fukaActId: route.query.fukaActId,
              },
            })
          }
          else {
            ElMessage.error(`编辑失败。${res.errors}`)
          }
        })
      }
      else {
        // 添加
        // router.push({ name: 'fukaactPrizeList' })
        PostTaskCreateData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.emptyFormData('fukaTaskFrom')
            router.push({
              name: 'fukaTaskList',
              query: {
                fukaActId: route.query.fukaActId,
              },
            })
          }
          else {
            ElMessage.error(`添加失败。${res.errors}`)
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

const OptionList = reactive({
  fukaOption: [],
})

onMounted(async () => {
  if (id) {
    await GetTaskDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('fukaTaskFrom')
    if (!(ruleForm.value.fukaActId)) {
      ruleForm.value.fukaActId = route.query.fukaActId ? Number(route.query.fukaActId) : ''
    }
  }

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('fukaTaskFrom', newValue)
    }
  }, { deep: true })

  // 获取福卡活动
  const fukaData: any = await GetFukaOption()
  if (fukaData.succeeded) {
    OptionList.fukaOption = fukaData.data
    nextTick(() => {
      OptionList.fukaOption = fukaData.data
    })
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="福卡活动" prop="fukaActId">
              <el-select v-model="ruleForm.fukaActId" filterable placeholder="请选择福卡活动">
                <el-option v-for="item in (OptionList.fukaOption as any[])" :key="item.fukaActId" :label="`${item.fukaActId}`" :value="item.fukaActId" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="状态">
              <el-switch
                v-model="ruleForm.taskStatus"
                :active-value="1"
                :inactive-value="-1"
                active-text="启用"
                inactive-text="停用"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="类型" prop="classId">
              <el-select v-model="ruleForm.classId" placeholder="请选择状态">
                <el-option label="新客专享福卡派送" :value="10" />
                <el-option label="好友助力抽福卡" :value="20" />
                <el-option label="下单解锁抽福卡" :value="30" />
                <el-option label="下单福卡随心兑" :value="31" />
                <el-option label="好友福卡转增" :value="40" />
                <el-option label="福利官派福" :value="50" />
              </el-select>
              <!-- <el-radio-group v-model="ruleForm.classId">
                <el-radio :value="1">
                  新用户赠送
                </el-radio>
                <el-radio :value="2">
                  好友助力成功
                </el-radio>
                <el-radio :value="3">
                  下单赠送机会
                </el-radio>
                <el-radio :value="3">
                  下单领取任意福卡
                </el-radio>
                <el-radio :value="3">
                  好友转增
                </el-radio>
                <el-radio :value="3">
                  添加福利官
                </el-radio>
              </el-radio-group> -->
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="自定义排序" prop="sort">
              <el-input v-model="ruleForm.sort" placeholder="请输入自定义排序" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="跳转路径" prop="linkUrl">
              <el-input v-model="ruleForm.linkUrl" placeholder="请输入跳转路径" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="上传图片">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="任务banner图" prop="taskPic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.taskPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'taskPic')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
